<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>局域网文件共享系统</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .server-info {
            background-color: #e9f7fe;
            border-left: 4px solid #007bff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .server-info h3 {
            margin-top: 0;
            color: #007bff;
        }
        .ip-address {
            font-weight: bold;
            color: #007bff;
            font-size: 18px;
        }
        .lan-access {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .lan-access h3 {
            margin-top: 0;
            color: #856404;
        }
        .lan-url {
            font-weight: bold;
            color: #856404;
            font-size: 16px;
            word-break: break-all;
        }
        .upload-section {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            margin-bottom: 30px;
            transition: border-color 0.3s;
        }
        .upload-section:hover {
            border-color: #007bff;
        }
        .upload-section.dragover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        .file-input {
            margin: 20px 0;
        }
        .file-input input[type="file"] {
            display: none;
        }
        .file-input label {
            display: inline-block;
            padding: 12px 24px;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .file-input label:hover {
            background-color: #0056b3;
        }
        .upload-btn {
            padding: 12px 30px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        .upload-btn:hover {
            background-color: #218838;
        }
        .upload-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .files-section {
            margin-top: 30px;
        }
        .files-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .files-table th, .files-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .files-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .files-table tr:hover {
            background-color: #f5f5f5;
        }
        .download-btn {
            padding: 6px 12px;
            background-color: #17a2b8;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .download-btn:hover {
            background-color: #138496;
        }
        .delete-btn {
            padding: 6px 12px;
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .delete-btn:hover {
            background-color: #c82333;
        }
        .status {
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
            text-align: center;
        }
        .status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .file-info {
            margin-top: 10px;
            font-size: 14px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📁 局域网文件共享系统</h1>
        
        <!-- 服务器信息 -->
        <div class="server-info">
            <h3>🖥️ 服务器信息</h3>
            <p>本机IP地址: <span id="localIP" class="ip-address">加载中...</span></p>
            <p>服务端口: <span class="ip-address">3005</span></p>
        </div>
        
        <!-- 局域网访问信息 -->
        <div class="lan-access">
            <h3>🌐 局域网访问</h3>
            <p>局域网内的其他设备可以通过以下地址访问:</p>
            <p id="lanUrls" class="lan-url">加载中...</p>
        </div>
        
        <!-- 上传区域 -->
        <div class="upload-section" id="uploadArea">
            <h2>📤 上传文件</h2>
            <p>将文件拖拽到此处或点击选择文件</p>
            
            <div class="file-input">
                <input type="file" id="fileInput" multiple>
                <label for="fileInput">选择文件</label>
            </div>
            
            <div class="file-info" id="fileInfo"></div>
            
            <button class="upload-btn" id="uploadBtn" disabled>上传文件</button>
        </div>
        
        <!-- 状态信息 -->
        <div id="statusMessage"></div>
        
        <!-- 文件列表 -->
        <div class="files-section">
            <h2>📂 共享文件列表</h2>
            <button id="refreshBtn">刷新列表</button>
            <table class="files-table">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>修改时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="filesList">
                    <tr>
                        <td colspan="4" style="text-align: center;">加载中...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        // 获取DOM元素
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const fileInfo = document.getElementById('fileInfo');
        const uploadBtn = document.getElementById('uploadBtn');
        const statusMessage = document.getElementById('statusMessage');
        const filesList = document.getElementById('filesList');
        const refreshBtn = document.getElementById('refreshBtn');
        const localIPSpan = document.getElementById('localIP');
        const lanUrlsDiv = document.getElementById('lanUrls');
        
        // 当前选中的文件
        let selectedFiles = [];
        
        // 页面加载完成后获取服务器信息和文件列表
        document.addEventListener('DOMContentLoaded', function() {
            loadServerInfo();
            loadFiles();
        });
        
        // 获取服务器信息
        function loadServerInfo() {
            fetch('/api/info')
            .then(response => response.json())
            .then(data => {
                localIPSpan.textContent = data.localIP;
                
                // 显示所有局域网访问地址
                if (data.localIPs && data.localIPs.length > 0) {
                    const urls = data.localIPs.map(ip => `http://${ip}:${data.port}`);
                    lanUrlsDiv.innerHTML = urls.map(url => `<div>${url}</div>`).join('');
                } else {
                    lanUrlsDiv.textContent = `http://${data.localIP}:${data.port}`;
                }
            })
            .catch(error => {
                console.error('获取服务器信息失败:', error);
                localIPSpan.textContent = '无法获取';
                lanUrlsDiv.textContent = '无法获取';
            });
        }
        
        // 文件输入变化事件
        fileInput.addEventListener('change', function(e) {
            selectedFiles = Array.from(e.target.files);
            updateFileInfo();
        });
        
        // 拖拽上传功能
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            selectedFiles = Array.from(e.dataTransfer.files);
            updateFileInfo();
        });
        
        // 更新文件信息显示
        function updateFileInfo() {
            if (selectedFiles.length > 0) {
                const totalSize = selectedFiles.reduce((sum, file) => sum + file.size, 0);
                fileInfo.textContent = `已选择 ${selectedFiles.length} 个文件，总大小: ${formatFileSize(totalSize)}`;
                uploadBtn.disabled = false;
            } else {
                fileInfo.textContent = '';
                uploadBtn.disabled = true;
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 上传文件
        uploadBtn.addEventListener('click', function() {
            if (selectedFiles.length === 0) {
                showStatus('请先选择文件', 'error');
                return;
            }
            
            // 创建FormData对象
            const formData = new FormData();
            
            // 添加所有选中的文件
            selectedFiles.forEach(file => {
                formData.append('file', file);
            });
            
            // 禁用上传按钮
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';
            
            // 发送上传请求
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showStatus(data.error, 'error');
                } else {
                    showStatus(`文件上传成功！`, 'success');
                    // 清空文件选择
                    fileInput.value = '';
                    selectedFiles = [];
                    fileInfo.textContent = '';
                    // 刷新文件列表
                    loadFiles();
                }
            })
            .catch(error => {
                showStatus(`上传失败: ${error.message}`, 'error');
            })
            .finally(() => {
                // 恢复上传按钮
                uploadBtn.disabled = false;
                uploadBtn.textContent = '上传文件';
            });
        });
        
        // 显示状态信息
        function showStatus(message, type) {
            statusMessage.innerHTML = `<div class="status ${type}">${message}</div>`;
            setTimeout(() => {
                statusMessage.innerHTML = '';
            }, 5000);
        }
        
        // 加载文件列表
        function loadFiles() {
            // 修改API端点路径
            fetch('/api/files')
            .then(response => response.json())
            .then(files => {
                if (files.error) {
                    filesList.innerHTML = `<tr><td colspan="4" style="text-align: center; color: red;">${files.error}</td></tr>`;
                    return;
                }
                
                if (files.length === 0) {
                    filesList.innerHTML = `<tr><td colspan="4" style="text-align: center;">暂无文件</td></tr>`;
                    return;
                }
                
                filesList.innerHTML = files.map(file => `
                    <tr>
                        <td>${file.name}</td>
                        <td>${formatFileSize(file.size)}</td>
                        <td>${new Date(file.modified).toLocaleString()}</td>
                        <td>
                            <a href="${file.url}" class="download-btn" target="_blank">下载</a>
                            <!-- 修改删除API端点路径 -->
                            <button class="delete-btn" onclick="deleteFile('${file.name}')">删除</button>
                        </td>
                    </tr>
                `).join('');
            })
            .catch(error => {
                filesList.innerHTML = `<tr><td colspan="4" style="text-align: center; color: red;">加载文件列表失败: ${error.message}</td></tr>`;
            });
        }
        
        // 删除文件
        function deleteFile(filename) {
            if (!confirm(`确定要删除文件 "${filename}" 吗？`)) {
                return;
            }
            
            // 修改删除API端点路径
            fetch(`/api/files/${encodeURIComponent(filename)}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showStatus(data.error, 'error');
                } else {
                    showStatus(data.message, 'success');
                    loadFiles(); // 刷新文件列表
                }
            })
            .catch(error => {
                showStatus(`删除失败: ${error.message}`, 'error');
            });
        }
        
        // 刷新按钮事件
        refreshBtn.addEventListener('click', loadFiles);
    </script>
</body>
</html>